import { createRouter, createWebHistory } from 'vue-router'
import { usePermissions } from '../stores/permission'
import { routes } from './routes'
import { URLS } from '@/common/urls'
import { hasPermission } from '@/common/util'
import { useToken } from '@/stores/app'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// VUE2中before是三个参数 而vue3中是两个参数，缺少next，用return代替
router.beforeEach((to, from) => {
  console.log('--from--', from, '--to--', to)
  const { title } = to.meta as any
  document.title = title || '花花'

  const { token } = useToken()
  const { permissions } = usePermissions()

  const isOk = hasPermission(permissions, `${to.meta.subject}`)
  if (!token && to.path !== URLS.LOGIN) {
    // next(URLS.LOGIN);
    return URLS.LOGIN
  } else if (to.meta.permiss && !isOk) {
    // next(URLS.PAGE_403);
    return URLS.PAGE_403
  } else {
    // next();
    return
  }
})

export default router
